package com.bite.system.service.user.impl;

import com.bit.common.security.handler.ServiceException;
import com.bite.common.core.enums.ResultCode;
import com.bite.system.domain.user.User;
import com.bite.system.domain.user.dto.UserDTO;
import com.bite.system.domain.user.dto.UserQueryDTO;
import com.bite.system.domain.user.vo.UserVO;
import com.bite.system.manager.UserCacheManager;
import com.bite.system.mapper.user.UserMapper;
import com.bite.system.service.user.IUserService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCacheManager userCacheManager;


    @Override
    public List<UserVO> list(UserQueryDTO userQueryDTO) {
        PageHelper.startPage(userQueryDTO.getPageNum(),userQueryDTO.getPageSize());
        List<UserVO> userVOList = userMapper.selectUserList(userQueryDTO);
        return userVOList;
    }

    //拉黑用户
    @Override
    public int updateStatus(UserDTO userDTO) {
        //判断用户是否存在
        User user = getUser(userDTO);
        user.setStatus(userDTO.getStatus());
        //缓存也要存
        userCacheManager.updateStatus(user.getUserId(),user.getStatus());
        return userMapper.updateById(user);
    }

    private User getUser(UserDTO userDTO) {
        User user = userMapper.selectById(userDTO.getUserId());
        if (user == null){
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return user;
    }
}
